package com.xxmw.transaction.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.common.utils.Assert;
import com.xxmw.transaction.common.utils.keygen.IdGenerator;
import com.xxmw.transaction.common.utils.keygen.Sequence;
import com.xxmw.transaction.model.app.User;
import com.xxmw.transaction.model.app.VipRecord;
import com.xxmw.transaction.service.app.IVipRecordService;
import com.xxmw.transaction.service.app.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author: yamoo
 * @create: 2020-07-08 17:06
 */
@Slf4j
@RestController
@RequestMapping("admin/appUser")
public class AdminUserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private IVipRecordService vipRecordService;

    @GetMapping("list")
    public R list(@RequestParam(required = false, defaultValue = "1") Integer page,
                  @RequestParam(required = false, defaultValue = "20") Integer pageSize,
                  @RequestParam(required = false) String username){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Assert.isNotNullOrEmpty(username), User::getUsername, username);
        IPage<User> result = userService.page(new Page<>(page, pageSize), wrapper);
        return R.ok(result);
    }


    @PostMapping("addVipTime")
    public R addVipTime (@RequestParam String username, @RequestParam Integer vipTime, @RequestParam BigDecimal amount) {
        User user = userService.getUser(username);

        VipRecord record = getVipRecord(user, amount, vipTime);
        vipRecordService.save(record);
        userService.addVipTime(username, vipTime);
        return R.ok();
    }


    /**
     * 获取实体类
     * @param user
     * @param amount
     * @param vipTime
     * @return
     */
    private VipRecord getVipRecord(User user, BigDecimal amount, Integer vipTime) {
        // 生成id
        IdGenerator idGenerator = Sequence.getInstance();
        String id = "TS"+idGenerator.generate().toString();

        VipRecord record = new VipRecord();
        record.setOrderId(id);
        record.setUserId(user.getId());
        record.setUsername(user.getUsername());
        record.setStatus(VipRecord.Status.FINISHED.getValue());
        record.setQuantity(amount);
        record.setMonth(vipTime);
        record.setCreateTime(new Date());
        record.setCreateUser(getUser().getUsername());

        return record;
    }
}
